<template>
	<div class="form-component-contariner">
		<el-tabs v-model="activeName">
			<el-tab-pane label="表单管理" name="form">
				<div class="head">
					<el-button type="primary" @click="createForm">创建表单</el-button>
				</div>
				<div class="table">
					<Table :tableData="formTableData">
						<template v-slot:btn>
							<el-table-column width="310px" align="center" label="操作">
								<template slot-scope="scope">
									<el-button size="mini" type="primary" class="set-btn" @click="editForm(scope.$index, scope.row)">编辑</el-button>
									<el-button size="mini" type="primary" class="set-btn" @click="settingProps(scope.$index, scope.row)">配置表单属性</el-button>
									<el-button size="mini" type="danger" class="del-btn" @click="delForm(scope.$index, scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</template>
					</Table>
				</div>
				<br />
				<div class="page">
					<PageSize :pages="searchData" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
				</div>
			</el-tab-pane>
			<AddForm :addFormDialog="showAddDialog" v-if="showAddDialog" :title="addFormTitle" @onCancal="cancelAddForm" @onOk="getAddForm" />
		</el-tabs>
	</div>
</template>

<script>
import Table from '../components/Table.vue';
import PageSize from '../components/PageSize.vue';

import AddForm from './AddForm.vue';
import { mapMutations, mapState } from 'vuex';
import '@zco/form-designer/dist/form-designer.css';
import { getFormTemplateList, createFormTemplate, updateFormTemplate, deleteFormTemplateWithId } from '@/api/api.js';
export default {
	name: 'form',
	components: {
		Table,
		PageSize,
		AddForm
	},
	data() {
		return {
			activeName: 'form',
			showAddDialog: false,
			addFormTitle: '新增表单',
			searchData: {
				isEmpty: true,
				page: 1,
				pageSize: 10,
				total: 10
			},
			formTableData: {
				sort: false,
				tableHead: [
					{
						label: '表单名称',
						prop: 'name'
					},
					{
						label: '创建时间',
						prop: 'createdAt'
					}
				],
				tableConent: [],
				showIndex: false,
				showCheck: false
			},
			// 表单ID
			formId: null
		};
	},
	computed: {
		...mapState({
			formList: state => state.form.formList,
			formName: state => state.form.formName
		})
	},
	mounted() {
		this.initFormList();
		this.formTableData.tableConent = JSON.parse(JSON.stringify(this.formList));
	},
	methods: {
		...mapMutations('form', ['SET_EDIT_FORM_NAME', 'SET_FORM_LIST']),
		// 获取表单列表数据
		async initFormList() {
			try {
				const { data } = await getFormTemplateList(this.searchData);
				this.searchData.total = data.data.count;
				const list = data.data.data.map(form => ({
					id: form.id,
					name: form.name,
					createdAt: this.$moment(form.createdAt).format('YYYY-MM-DD HH:mm:ss'),
					fields: form.fields ? form.fields : {}
				}));
				this.$store.commit('SET_FORM_LIST', list);
				this.formTableData.tableConent = this.formList;
			} catch (e) {
				// this.$message.error('获取表单列表页数据失败！');
				this.$requestApiError(e, () => {
					this.$router.push('/');
				});
			}
		},
		// 分页
		changePageSize(pageSize) {
			this.searchData.pageSize = pageSize;
			this.searchData.page = 1;
			this.initFormList();
		},
		changeCurrentPage(page) {
			this.searchData.page = page;
			this.initFormList();
		},

		// 创建表单
		createForm() {
			this.$store.commit('SET_EDIT_FORM_NAME', '');
			this.addFormTitle = '新增表单';
			this.formId = null;
			this.showAddDialog = true;
		},

		// 编辑表单
		editForm(index, data) {
			this.addFormTitle = '编辑表单';
			this.formId = data.id;
			this.$store.commit('SET_EDIT_FORM_NAME', data.name);
			this.showAddDialog = true;
		},

		// 配置业务属性
		settingProps(index, row) {
			let formData = this.formList.find(form => form.id === row.id);
			let data = JSON.parse(sessionStorage.getItem('editFormData')) || {};
			const key = String(row.id);
			if (formData) {
				data[key] = formData.fields;
				data[key].name = row.name;
			} else {
				data[key] = row.fields;
				data[key].name = row.name;
			}
			sessionStorage.setItem('editFormData', JSON.stringify(data));
			// 添加导航菜单
			let menu = {
				meta: {}
			};
			const { meta, name, path } = this.$route;
			menu.name = `${name}/${row.id}`;
			menu.meta.jumpNo = meta.jumpNo + 1;
			menu.meta.sceneName = row.name;
			menu.meta.keepAlive = false;
			menu.meta.title = `${row.name}详情`;
			menu.meta.data = row;
			menu.meta.toPath = `${meta.toPath}/${row.id}`;
			menu.path = `${path}/${row.id}`;
			this.$store.commit('SET_TAG_LIST', menu);

			this.$router.push({ name: 'settingform', params: { id: row.id, name: row.name } });
		},

		// 删除表单
		async delForm(index, data) {
			this.$confirm(`确定要删除 ${data.name} 表单, 是否继续?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(async () => {
					try {
						await deleteFormTemplateWithId(data.id);
						this.$message.success('删除表单成功！');
						// 删除导航菜单
						this.$store.commit('CLEAR_TAG', `form/${data.id}`);
					} catch (e) {
						switch (e.code) {
							case '1002':
								this.$message.error('删除表单失败，表单已被业务场景使用！');
								break;
							case '1101':
								this.$message.error('删除表单失败，请求权限拒绝！');
								break;
							case '1201':
								this.$message.error('删除表单失败，该表单正在被使用中！');
								break;
							default:
								this.$message.error('删除表单失败！');
								break;
						}
					} finally {
						this.initFormList();
					}
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},

		// 取消新增表单
		cancelAddForm() {
			this.showAddDialog = false;
		},

		// 确认新增表单
		async getAddForm(form) {
			let data = { name: form.name, id: this.formId };
			// 新增表单
			if (!this.formId) {
				try {
					await createFormTemplate(data);
					this.$message.success('创建表单成功！');
				} catch (e) {
					switch (e.code) {
						case 1002:
							this.$message.error('创建表单，表单已存在');
							break;
						case 1101:
							this.$message.error('创建表单，请求权限拒绝！');
							break;
						case 1201:
							this.$message.error('编辑表单失败，该表单正在被使用中！');
							break;
						default:
							this.$message.error('创建表单失败！');
							break;
					}
				} finally {
					this.initFormList();
					this.showAddDialog = false;
				}
				// 编辑表单
			} else {
				try {
					await updateFormTemplate(data);
					this.$message.success('编辑表单成功！');
				} catch (e) {
					switch (e.code) {
						case 1002:
							this.$message.error('编辑表单失败，表单已存在');
							break;
						case 1101:
							this.$message.error('编辑表单失败，请求权限拒绝！');
							break;
						case 1201:
							this.$message.error('编辑表单失败，该表单正在被使用中！');
							break;
						default:
							this.$message.error('编辑表单失败！');
							break;
					}
				} finally {
					this.initFormList();
					this.showAddDialog = false;
				}
			}
		}
	}
};
</script>

<style lang="less" scoped>
.form-component-contariner {
	.head {
		padding-bottom: 20px;
		.el-button {
			width: 84px;
			height: 36px;
			background-color: #6384fe;
			padding: 0;
		}
	}
	.del-btn {
		color: #fff;
		background-color: #ef5753;
	}
	.set-btn {
		color: #fff;
		background-color: #6384fe;
	}
	.disabled {
		background-color: #999;
	}
}
</style>
